import * as echarts from 'echarts';

const PORT_NAME = {
    xuweiPort: '徐圩港区',
    ganyuPort: '赣榆港区',
    elderPort: '连云港区'
};
const date = new Array(10).fill(0).map((v, i) => ((2005 + (i * 2)).toString()));

// tip内圆点的style
const styles = 'display:inline-block;width:8px;height:8px;border-radius:4px;margin-right:6px;';
const legend = {
    icon: 'rect',
    itemWidth: 14,
    itemHeight: 5,
    itemGap: 13,
    data: Object.values(PORT_NAME),
    right: '4%',
    top: 25,
    textStyle: {
        fontSize: 12,
        color: '#ccc',
    },
};

export const genHandlingCapacity = (data) => {
    return {
        title: {
            text: '连云港港区历年货物吞吐量（万TEU）',
            textStyle: {
                color: '#eee',
                fontSize: 14,
            },
            top: 0,
            left: 'center',
        },
        // 鼠标hover的tip
        tooltip: {
            // 坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用。
            trigger: 'axis',
            // 坐标拾取指示器，可以是shadow、line、cross和none
            axisPointer: {
                type: 'shadow',
            },
            // tip的内容
            formatter: params => {
                const tooltipTitle = parseInt(params[0].name) > 2019 ? `${params[0].name}（预测）` : params[0].name;
                return `
          <p style="text-align:left;font-size:12px;line-height:18px">${tooltipTitle}</p>
          ${params.map(({ color, seriesName, value }) => {
                            return value !== '-'
                                ? `
                <p style="text-align:left;line-height:18px">
                  <i class="chart-circle" style="${styles}background-color:${color.colorStops[0].color}"></i>
                  ${seriesName}：${value.toFixed(2)}(万TEU)
                </p>
              `
                                : null;
                        })
                        .join('')}
        `;
            },
        },
        xAxis: {
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
            axisLabel: {
                textStyle: {
                    fontSize: 10,
                    color: '#666',
                },
            },
            type: 'category',
            boundaryGap: true,
            data: date && date.map(year => `${year}年`),
        },
        yAxis: {
            inverse: false,
            splitNumber: 5,
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
            axisLabel: {
                textStyle: {
                    fontSize: 10,
                    color: '#666',
                },
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(168, 178, 185, .1)',
                },
            },
            type: 'value',
        },
        legend: legend,
        grid: {
            top: '50px',
            left: '0',
            right: '0',
            bottom: '0',
            containLabel: true,
        },
        series: (() => {
            let series = [];
            Object.keys(data).forEach(phase => {
                series = series.concat(Object.keys(data[phase]).map(port => ({
                    type: "bar",
                    name: PORT_NAME[port],
                    barWidth: '10px',
                    // 数据显示的轴，若不同数据在同一个轴，则会叠加显示
                    stack: '1',
                    data: data[phase][port],
                    itemStyle: {
                        normal: {
                            // 生成渐变颜色
                            // 线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: port === 'xuweiPort' ? '#8bd46e' :
                                        port === 'ganyuPort' ? '#cc99ff' : '#248ff7',
                                },
                                {
                                    offset: 1,
                                    color: port === 'xuweiPort' ? '#09bcb7' :
                                        port === 'ganyuPort' ? '#cc66ff' : '#6851f1',
                                },
                            ]),
                            barBorderRadius: port === 'xuweiPort' ? [0, 0, 5, 5] :
                                port === 'ganyuPort' ? 0 : [5, 5, 0, 0],
                            borderType: phase === 'prediction' ? 'dashed' : 'solid',
                            opacity: phase === 'prediction' ? '0.3' : '1',
                        },
                    }
                })))
            })
            return series;
        })()
    }
}

export const genBoundStatistical = (data) => {
    return {
        title: {
            text: '港口岸线长度（米）',
            textStyle: {
                color: '#eee',
                fontSize: 14,
            },
            top: 0,
            left: 'center',
        },
        tooltip: {
            formatter: params => {
                const currentDate = parseInt(params[0].name);
                const tooltipTitle = currentDate > 2019 ? `${params[0].name}（预测）` : params[0].name;
                return `
          <p style="text-align:left;font-size:12px;line-height:18px">${tooltipTitle}</p>
          ${params
                        .map(({ color, seriesName, value, seriesId }) => {
                            if (currentDate === 2019) {
                                return value !== '-' && seriesId.indexOf(0) !== -1
                                    ? `
                <p style="text-align:left;line-height:18px">
                  <i class="chart-circle" style="${styles}background-color:${color}"></i>
                  ${seriesName}：${value.toFixed(2)}米
                </p>
              `
                                    : null;
                            } else {
                                return value !== '-'
                                    ? `
                <p style="text-align:left;line-height:18px">
                  <i class="chart-circle" style="${styles}background-color:${color}"></i>
                  ${seriesName}：${value.toFixed(2)}米
                </p>
              `
                                    : null;
                            }
                        })
                        .join('')}
        `;
            },
        },
        grid: {
            top: '50px',
            left: '20px',
            right: '0',
            bottom: '0',
            containLabel: true,
        },
        xAxis: {
            data: date && date.map(year => `${year}年`),
        },
        yAxis: {
            splitLine: {
                lineStyle: {
                    color: 'rgba(168, 178, 185, .1)',
                },
            },
        },
        legend: legend,
        series: (() => {
            let series = [];
            // 记录2019年的数据，后面的是预测数据，使用虚线，要将19年数据加到开头，否则会断开
            let lastStatistical = {};
            Object.keys(data).forEach((phase, index) => {
                series = series.concat(Object.keys(data[phase]).map(port => {
                    const portData = data[phase][port];

                    if (index === 0) {
                        lastStatistical[port] = portData[date.indexOf('2019')];
                    } else {
                        portData[date.indexOf('2019')] = lastStatistical[port];
                    }
                    return {
                        name: PORT_NAME[port],
                        data: portData,
                        smooth: false,
                        symbol: 'emptyCircle',
                        symbolSize: 4,
                        showAllSymbol: true,
                        lineStyle: {
                            normal: {
                                type: index ? 'dashed' : 'solid',
                                width: 1.5,
                                color: port === 'xuweiPort' ? '#8bd46e' :
                                    port === 'ganyuPort' ? '#cc99ff' : '#248ff7',
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: port === 'xuweiPort' ? '#8bd46e' :
                                    port === 'ganyuPort' ? '#cc99ff' : '#248ff7',
                            },
                        }
                    }
                }))
            })
            return series;
        })()

    }
}

export const getBerthStatistical = (data) => {
    const emphasisStyle = {
        color: 'rgb(119, 251, 227)',
        borderColor: 'rgb(119, 251, 227, 0.5)'
    };
    return {
        baseOption: {
            timeline: {
                axisType: 'category',
                autoPlay: true,
                playInterval: 1500,
                data: date.slice(0, -2),
                lineStyle: {
                    color: '#666',
                },
                itemStyle: {
                    emphasis: emphasisStyle,

                },
                controlStyle: {
                    emphasis: emphasisStyle,
                    normal: {
                        itemSize: 16,
                        borderColor: '#666',
                    },
                    showPlayBtn: false,
                    // showPrevBtn:false,
                    // showNextBtn:false
                },
                symbolSize: 8,
                checkpointStyle: {
                    symbolSize: 8,
                    color: 'rgb(119, 251, 227)',
                    borderColor: 'rgb(119, 251, 227, 0.5)'
                },
                label: {
                    emphasis: emphasisStyle,
                    normal: {
                        color: '#666',
                    },
                    formatter: function (s) {
                        return (new Date(s)).getFullYear();
                    }
                }
            },
            tooltip: {
                backgroundColor: 'rgba(255,255,255,0.80)',
                borderColor: '#F1F1F1',
                borderWidth: 1,
                padding: [8, 16],
                textStyle: {
                    color: '#666',
                    fontSize: 10,
                },
                extraCssText: 'box-shadow:0 1px 4px 0 rgba(0,0,0,0.20);border-radius:4px;',
                formatter: params => {
                    if (params && params.name && params.color && params.color.colorStops[0] && params.color.colorStops[0].color)
                        return `
            <p style="text-align:left;line-height:18px">
              <i class="chart-circle" style="${styles}background-color:${params.color.colorStops[0].color}"></i>
              ${params.name}
            </p>
            <p style="text-align:left;line-height:18px">
              数量：${params.data.value.toFixed(0)}个
            </p>
            <p style="text-align:left;line-height:18px">
              占比：${params.percent.toFixed(2)}%
            </p>
          `;
                },
            },
            legend: {
                left: '4%',
                top: '8%',
                orient: 'vertical',
                ...legend
            },
            title: {
                textStyle: {
                    color: '#eee',
                    fontSize: 14,
                },
                top: 0,
                left: 'center',
            },
            series: [
                {
                    type: 'pie',
                    center: ['50%', '45%'],
                    radius: '50%',
                    itemStyle: {
                        normal: {
                            color: (params) => (
                                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    {
                                        offset: 0,
                                        color: params.name === '徐圩港区' ? '#8bd46e' :
                                            params.name === '赣榆港区' ? '#cc99ff' : '#248ff7',
                                    },
                                    {
                                        offset: 1,
                                        color: params.name === '徐圩港区' ? '#09bcb7' :
                                            params.name === '赣榆港区' ? '#cc66ff' : '#6851f1',
                                    },
                                ])
                            ),
                            label: {
                                fontSize: 12,
                                color: '#ccc'
                            },
                            labelLine: {
                                length: 5,
                            },
                        },
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    z: 100
                }
            ]
        },
        options: (() => {
            let options = []
            for (const port in data.statistical) {
                data.statistical[port].forEach((item, index) => {
                    if (index < 8) {
                        !options[index] && options.push({
                            title: {
                                text: `连云港港区${2005 + index * 2}年泊位数量`
                            },
                            series: [{
                                data: []
                            }]
                        });
                        let pieData = options[index].series[0].data;
                        pieData.push({
                            name: PORT_NAME[port],
                            value: item
                        })
                    }
                })
            }
            return options
        })()

    }
}